<script setup>
import { ref,reactive} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const searchDept = reactive({
    name:""
})

//表格数据
const users = ref([])


// 分页查询参数
const queryUser = reactive({
  pageSize:9,
  pageNum:1,
  userUsername:'',
})
const total = ref(0)

const handlePageChange = (currentPageValue) => {
    queryUser.pageNum = currentPageValue
    userList()
}

//获取用户列表
import { queryList,deleteById,userAddService,userUpdateService } from '../../api/User'
const userList = async()=>{
    let result = await queryList(queryUser)
    total.value = result.data.data.total
    // console.log("数据："+total.value)
    users.value = result.data.data.data
    // console.log("数据："+users.value)
    
}
userList()

//删除用户数据方法
const deleteUser = (userId)=>{
     ElMessageBox.confirm(
    '你确定要删该条数据吗？（不可恢复）',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      await deleteById(userId)
      userList()  
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const optName = ref('')

const handleSelectionChange = (val) => {
  console.log(val)
}

//控制弹出框出现
const dialogTableVisible = ref(false)
const show = (row)=>{
    userModel.value.userId = row.userId
    userModel.value.userUsername = row.userUsername
    userModel.value.userNickname = row.userNickname
    userModel.value.userPassword = row.userPassword
    userModel.value.userAvatar = row.userAvatar
    userModel.value.admin = row.admin
    dialogTableVisible.value=true
}

const clean = ()=>{
    userModel.value.userId = null
    userModel.value.userUsername = ''
    userModel.value.userNickname = ''
    userModel.value.userPassword = ''
    userModel.value.userAvatar = ''
    userModel.value.admin = null
}


const userModel = ref({
    userId:null,
    userUsername:'',
    userNickname:'',
    userPassword:'',
    userAvatar:'',
    admin:null
})

//限制上传类型、大小
const beforeAvatarUpload = (file)=>{
    const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
    const isValidSize = file.size / 1024 / 1024 < 2
    if (!isValidType) {
        ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
        return false
    }

    if (!isValidSize) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }

    return true
}

const handleAvatarSuccess = (response, file)=>{
    userModel.value.userAvatar = response.avatarUrl || URL.createObjectURL(file.raw)
}

const addUser = async()=>{
    await userAddService(userModel.value)
    userList()
    dialogTableVisible.value = false
}
const updateUser = async()=>{
    await userUpdateService(userModel.value)
    userList()
    dialogTableVisible.value = false
}

const centerDialogVisible = ref(false)

import { userRoleFindByIdService,userRoleAddService } from '../../api/UserRole'
const userRoles = ref({
    userId:null,
    roles:[]
})
//控制分配角色弹窗出现
const showDia = async(userId)=>{
    let result = await userRoleFindByIdService(userId)
    for(let i = 0;i < result.data.data.length;i++){
        userRoles.value.roles.push(result.data.data[i].roleId)
    }
    userRoles.value.userId = userId
    centerDialogVisible.value = true
}

import { roleListService } from '../../api/Role'
//获取角色数据
const roles = ref([])
const roleList = async()=>{
    let result = await roleListService();
    roles.value = result.data.data
    console.log(roles.value)
}
roleList()

const userRoleClean = ()=>{
    userRoles.value.userId = null
    userRoles.value.roles = []
}

const editUserRole = async()=>{
    await userRoleAddService(userRoles.value.userId, userRoles.value.roles)
    centerDialogVisible.value = false
    userList()
}

//文件上传请求头token设置
const headers = ref({
    "token":localStorage.getItem('token')
}) 


</script>
<template>
    <div class="container">
        <el-card style="max-width: 100%;height: 100%;">
            <!-- 搜索栏 -->
            <div class="search">
                    <el-form :inline="true" :model="queryUser" class="demo-form-inline">
                        <el-form-item label="名称">
                            <el-input v-model="queryUser.userUsername" placeholder="请输入用户名称" clearable />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="userList">查询</el-button>
                        </el-form-item>
                         <el-form-item>
                            <el-button type="primary" @click="clean();dialogTableVisible = true;optName = '新增用户'">新增</el-button>
                        </el-form-item>
                    </el-form>
            </div>
            <!-- 表格展示数据 -->
            <div class="content">

                <el-table 
                    :data="users" 
                    border 
                    @selection-change="handleSelectionChange"
                    style="width: 100%">
                    <el-table-column prop="userId" label="编号" width="80"></el-table-column>
                    <el-table-column prop="userUsername" label="用户名称" width="100"></el-table-column>
                    <el-table-column prop="userNickname" label="昵称" width="100"></el-table-column>
                    <el-table-column prop="userPassword" label="密码"></el-table-column>
                    <el-table-column prop="userAvatar" label="用户头像"></el-table-column>
                    <el-table-column label="管理员" width="80">
                        <template #default="scope">
                            <el-tag v-if="scope.row.admin === 1" type="success">是</el-tag>
                            <el-tag v-else type="info">否</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" >
                        <template #default="scope">
                        <el-button link type="primary" size="small" @click="show(scope.row);optName = '编辑用户'">编辑</el-button>
                        <el-button link type="danger" size="small" @click="deleteUser(scope.row.userId)">删除</el-button>
                        <el-button link type="primary" size="small" @click="showDia(scope.row.userId)">分配角色</el-button>
                        </template>
                    </el-table-column>
                </el-table>

            </div>
            <!-- 分页栏-->
            <div class="page">
                <el-pagination layout="prev, pager, next" :total="total" @current-change="handlePageChange"></el-pagination>
            </div>
                    <!-- 添加分类弹窗 -->
            <el-dialog v-model="centerDialogVisible" @close ="userRoleClean" title="分配角色" width="30%">
                <el-form label-width="100px" style="padding-right: 30px">
                    <div>
                        <el-checkbox-group v-model="userRoles.roles">
                            <el-checkbox v-for="role in roles" :key="role.roleId" :label="role.roleName" :value="role.roleId"  size="large" />
                        </el-checkbox-group>
                    </div>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="centerDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="editUserRole()"> 确认 </el-button>
                    </span>
                </template>
            </el-dialog>
        </el-card>

    <!-- 用户编辑/新增弹窗 -->
    <el-dialog v-model="dialogTableVisible" 
        :title="optName" width="800"
        @close="clean">
        <el-form :model="userModel" ref="formRef" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userUsername">
          <el-input v-model="userModel.userUsername" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword" label-width="80px">
          <el-input type="password" v-model="userModel.userPassword" placeholder="建议初始密码为6个1"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="userNickname" label-width="80px">
          <el-input v-model="userModel.userNickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <!-- 头像上传 -->
        <el-form-item label="头像" label-width="80px">
            <el-upload
                class="avatar-uploader"
                :action="'http://localhost:8080/upload'"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
            >
                <div style="position: relative; width: 100%; height: 100%">
                <el-avatar
                    v-if="userModel.userAvatar"
                    :src="userModel.userAvatar"
                    size="large"
                    style="width: 100px; height: 100px;"
                />
                <el-icon v-else class="avatar-uploader-icon">
                    <Plus />
                </el-icon>
                </div>
            </el-upload>
        </el-form-item>

        <!--选择是否是管理员-->
        <el-form-item label="用户管理">
             <el-radio-group v-model="userModel.admin">
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="0" size="large">否</el-radio>
        </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="optName == '新增用户'?addUser():updateUser()">确定</el-button>
        </span>
      </template>
    </el-dialog>

    </div>
</template>
<style lang="css" scoped>

    .container{
        padding: 20px;
    }

    .search{
        border-bottom: 1px solid #ccc;
    }

    .content{
        margin-top:20px;
    }

    .page{
        margin-top: 20px;
    }

    
</style>